<?php
/**
 * Created by PhpStorm.
 * User: xutao
 * Date: 2018/11/8
 * Time: 11:09
 */
//管理员账号
namespace app\admin\model;
use think\Db;
use think\Loader;
use think\Model;

class Admin extends Model{
    //表名
    protected $table = 'admin';
    public function GetGroupidAttr($groupid){
        $group = AuthGroup::all($groupid);
        return $group;

    }
    //密码修改器
    public function SetPasswordAttr($pwd){
        return md5($pwd);
    }
    //角色
    public function SetGroupidAttr($groupid){
        return implode(',',$groupid);
    }
    public static function get_access($id){
        $admin = self::where('id',$id)->find()->getData();
        $data = [];
        $re = Db::table('auth_group')->where('id','in',explode(',',$admin['groupid']))->field('rules')->select();
        if($re){
            foreach ($re as $k=>$v){
                $data = array_merge(explode(',',$v['rules']),$data);
            }
        }
       $data = array_unique($data);//重
        return $data;
    }

    //添加
    public function add($data){
        //验证字段
        $AdminValidate  = Loader::validate('AdminValidate');
        $check = $AdminValidate->check($data);
//        return json(['code'=>2,'data'=>$data,'msg'=>'该账号已存在']);
        if(!$check) return json(['code'=>1,'data'=>$AdminValidate->getError(),'msg'=>$AdminValidate->getError()]);
        //查询是否存在该账号
        $is_cunzai = self::where('username','=',$data['username'])->find();
        if($is_cunzai) return json(['code'=>2,'data'=>'','msg'=>'该账号已存在']);
        $re = $this->allowField(true)->save($data);
        if(!$re) return json(['code'=>3,'data'=>'','msg'=>'添加失败']);
        return json(['code'=>200,'data'=>'','msg'=>'添加成功']);
    }


    //更新
    public function update_data($data){
        $AdminValidate  = Loader::validate('AdminValidate');
        $check = $AdminValidate->check($data);
        if(!$check) return json(['code'=>1,'data'=>$AdminValidate->getError(),'msg'=>$AdminValidate->getError()]);
        //查询账号是否存在
        $is_cunzai = self::where('username',$data['username'])->where('id','<>',$data['id'])->find();
        if($is_cunzai) return json(['code'=>2,'data'=>'','msg'=>'该账号已存在']);
        if(!$data['portrait']) {
            unset($data['portrait']);
        }
        if($data['password'] == ''){
            unset($data['password']);
        }
        $re = $this->allowField(true)->save($data,['id'=>$data['id']]);
        if(isset($re)) return json(['code'=>200,'data'=>'','msg'=>'修改成功']);


    }
}